package com.pzhu.until;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;

@Component
public class JwtTokenUntil {
    //颁布者
    private static final String issuer = "example.com";
    private static final String audience = "user";
    //有效天数
    private static final int expiresIn = 3;
    //密钥
    private static final String secret = "jwt";


    public static String generate(TokenClaim... claims) {

        JWTCreator.Builder token = JWT.create()
                .withAudience(audience)
                .withIssuer(issuer)
                .withExpiresAt(new Date(System.currentTimeMillis() + expiresIn * 24 * 60 * 60 * 60));
        Arrays.asList(claims).forEach(claim -> token.withClaim(claim.getName(), claim.getValue()));

        return token.sign(Algorithm.HMAC256(secret));
    }

    public static DecodedJWT verify(String token) {
        return JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
    }

    public static Claim getClaim(HttpServletRequest request, String name) {
        String token = request.getHeader("token");
        DecodedJWT verify = verify(token);
        Claim claim = verify.getClaim(name);
        return claim;
    }
}
